
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

import org.w3c.dom.Document;

import com.facebook.api.*;
import com.facebook.api.schema.*;


/**
 * Servlet implementation class for Servlet: HomeServlet
 *
 */
 public class HomeServlet extends FacebookServlet implements javax.servlet.Servlet {
   static final long serialVersionUID = 1L;
   
    /* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public HomeServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		FacebookRestClient facebook = getAuthenticatedFacebookClient(request, response);
	      if ( facebook != null) {
	         if ( getUserInfos(request, facebook) ) {
	        	request.setAttribute("FB_APP_URL", FacebookServlet.FB_APP_URL);
	        	request.setAttribute("FB_API_KEY", FacebookServlet.FB_API_KEY);
	        	request.setAttribute("FB_APP_NAME", FacebookServlet.FB_APP_NAME);

	        	request.setAttribute("sessionKey", facebook._getSessionKey());
	        	response.setHeader("CACHE-CONTROL", "NO-CACHE");
	            request.getRequestDispatcher("home.jsp").forward(request, response);
	         }
	      }
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}   	 
	
	private boolean getUserInfos(HttpServletRequest request,
			FacebookRestClient fbrclient) {

		try {
			long myID = fbrclient.users_getLoggedInUser();

			EnumSet<ProfileField> fields = EnumSet.of(
					com.facebook.api.ProfileField.NAME);

			ArrayList<Long> users = new ArrayList<Long>();
			users.add(myID);
					
			System.out.println(users);

			// recuperation des informations
			fbrclient.users_getInfo(users, fields);
			UsersGetInfoResponse usersInfo = (UsersGetInfoResponse) fbrclient
					.getResponsePOJO();

			request.setAttribute("userName", usersInfo.getUser().get(0).getName());
			//request.setAttribute("uid", usersInfo.getUser().get(0).getUid());

			
		} catch (FacebookException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
}